package com.dayaokeji.rhythmschoolstudent.utils;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.Typeface;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v4.app.Fragment;

import com.dayaokeji.server_api.domain.UserInfo;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;

import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;
import top.zibin.luban.Luban;

/**
 * Created by Gorden on 2017/12/28.
 */

public class ImageUtil {

    private static final String ROOT_PATH = Environment.getExternalStorageDirectory().getAbsolutePath();
    private static final String APP_PATH = ROOT_PATH+File.separator+"rhythmschool"+File.separator;
    public static final String TEMP_IMAGES_DIR = APP_PATH+"temp_images_dir"+File.separator;

    private static File cameraFile;


    /**
     * 打开相机获取图片
     *
     * @param activity    activity
     * @param requestCode requestCode
     */
    public static void captureImageByCamera(Activity activity, int requestCode) {
        try {
            if (newCameraIntent(activity) != null) {
                activity.startActivityForResult(newCameraIntent(activity), requestCode);
            }
        } catch (ActivityNotFoundException e) {
            ToastUtils.warning("无法打开相机");
        }
    }

    /**
     * 打开相机获取图片
     *
     * @param fragment    fragment
     * @param requestCode requestCode
     */
    public static void captureImageByCamera(Fragment fragment, int requestCode) {
        try {
            fragment.startActivityForResult(newCameraIntent(fragment.getActivity()), requestCode);
        } catch (ActivityNotFoundException e) {
            ToastUtils.warning("无法打开相机");
        }
    }

    private static Intent newCameraIntent(Context context) {
        cameraFile = createTempImageFile(context);
        Intent intent;
        Uri pictureUri;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            ContentValues contentValues = new ContentValues(1);
            contentValues.put(MediaStore.Images.Media.DATA, cameraFile.getAbsolutePath());
            pictureUri = context.getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,contentValues);
        }else{
            intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            pictureUri = Uri.fromFile(cameraFile);
        }
        intent.putExtra(MediaStore.EXTRA_OUTPUT, pictureUri);
        return intent;
    }

    /**
     * 创建临时图片文件File对象
     *
     * @param context context
     * @return 图片File对象
     */
    private static File createTempImageFile(Context context) {
        File cacheDir = context.getExternalCacheDir();
        if (cacheDir == null) cacheDir = context.getCacheDir();
        String dirPath = TEMP_IMAGES_DIR;
        File dir = new File(dirPath);
        if (!dir.isDirectory()){
            dir.mkdirs();
        }
        return new File(dirPath+System.currentTimeMillis() + ".jpg");
    }

    /**
     * 获取最后调用相机传入的图片File
     *
     * @return 图片File
     */
    public static File getCaptureImageFile() {
        try {
            return cameraFile;
        } finally {
            cameraFile = null;
        }
    }


    @SuppressLint("StaticFieldLeak")
    public static Observable<File> ImageWaterMarkTask(final Context context, File file) {
        return Observable.just(file).map(new Function<File, File>() {
            @Override
            public File apply(File file) throws Exception {
                final List<File> files = Luban.with(context).load(file).get();
                if (files !=null && files.size() > 0) {
                    return files.get(0);
                }else{
                    return file;
                }
            }
        }).map(new Function<File, File>() {
            @Override
            public File apply(File file) throws Exception {
                if (file != null) {
                    final UserInfo userInfo = UserUtils.getUserInfo();
                    StringBuilder builder = new StringBuilder();
                    builder.append(userInfo.getName());
                    builder.append("-");
                    builder.append(userInfo.getWorkNo());
                    builder.append("-@-");
                    builder.append(DateUtils.format(System.currentTimeMillis(),DateUtils.FORMAT_DATETIME_SHORT2));
                    return waterMark(file,builder.toString());
                }else{
                    return null;
                }
            }
        }).subscribeOn(Schedulers.io()).subscribeOn(AndroidSchedulers.mainThread());
    }

    /**
     * 给图片打水印
     * @param file
     * @param str
     * @return
     */
    private static File waterMark(File file, String str) {
        final BitmapFactory.Options options = new BitmapFactory.Options();
        Bitmap bitmap = BitmapFactory.decodeFile(file.getAbsolutePath(),options);
        int destWidth = bitmap.getWidth();
        int destHeight = bitmap.getHeight();
        Bitmap newBitmap = Bitmap.createBitmap(destWidth, destHeight, Bitmap.Config.ARGB_8888); //定好宽高的全彩bitmap
        Canvas canvas = new Canvas(newBitmap);//初始化画布绘制的图像到icon上

        Paint photoPaint = new Paint(); //建立画笔
        photoPaint.setDither(true); //获取跟清晰的图像采样
        photoPaint.setFilterBitmap(true);//过滤一些

        Rect src = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight());//创建一个指定的新矩形的坐标
        Rect dst = new Rect(0, 0, destWidth, destHeight);//创建一个指定的新矩形的坐标
        canvas.drawBitmap(bitmap, src, dst, photoPaint);//将photo 缩放或则扩大到 dst使用的填充区photoPaint

        Paint textPaint = new Paint(Paint.ANTI_ALIAS_FLAG | Paint.DEV_KERN_TEXT_FLAG);//设置画笔
        textPaint.setTextSize(destWidth/30);//字体大小
        textPaint.setTextAlign(Paint.Align.CENTER);
        textPaint.setTypeface(Typeface.DEFAULT_BOLD);//采用默认的宽度
        textPaint.setAntiAlias(true);  //抗锯齿
        textPaint.setStyle(Paint.Style.FILL);
        textPaint.setColor(Color.WHITE);//采用的颜色
        textPaint.setShadowLayer(1f, 0f, 1f, Color.LTGRAY);
        canvas.drawText(str, destWidth / 2, destHeight - 45, textPaint);//绘制上去字，开始未知x,y采用那只笔绘制
//        canvas.save(Canvas.ALL_SAVE_FLAG);
        canvas.save();
        canvas.restore();
        bitmap.recycle();

        return saveWaterMarkFile(newBitmap);
    }

    /**
     * 保存水印图片文件
     * @param bitmap
     * @return
     */
    private static File saveWaterMarkFile(Bitmap bitmap) {
        String dirPath = TEMP_IMAGES_DIR;
        File dir = new File(dirPath);
        if (!dir.isDirectory()){
            dir.mkdirs();
        }
        File file = new File(dirPath + System.currentTimeMillis() + "_mark.jpg");
        if (!file.exists()){
            try {
                file.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        if (file.exists()) {
            FileOutputStream outputStream = null;
            try {
                outputStream = new FileOutputStream(file);
                bitmap.compress(Bitmap.CompressFormat.JPEG, 100, outputStream);
                return file;
            } catch (FileNotFoundException e) {
                e.printStackTrace();
                return null;
            } finally {
                if (outputStream != null) {
                    try {
                        outputStream.flush();
                        outputStream.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
        return null;
    }

    public interface WaterMarkFileCallback{
        void call(File file);
    }
}
